import { defineComponent, computed, inject, ref, onMounted, watch, watchEffect } from "vue";

export default defineComponent({
    props: {
        itemIndex: { type: Number },
        block: { type: Object },
        changeBlockItem: { type: Function }
    },
    setup(props) {

        const blockStyle = computed(() => {
            return {
                top: props.block.top + 'px',
                left: props.block.left + 'px',
                zIndex: props.block.zIndex,
            }
        })

        const config = inject('config')

        const blockRef = ref(null)

        const componentRender = () => {
            return config.componentMap[props.block.key].render(props.block?.props)
        }

        onMounted(() => {
            const { offsetWidth, offsetHeight } = blockRef.value
            // 给原数据中添加width,height
            let items = { ...props.block }
            // 拖拽后鼠标让元素位于的中间
            if (props.block.alignCenter) {
                items = {
                    ...props.block,
                    top: props.block.top - offsetHeight / 2,
                    left: props.block.left - offsetWidth / 2,
                    alignCenter: false,
                }
            }
            items.width = offsetWidth
            items.height = offsetHeight
            console.log('props', props)
            props.changeBlockItem && props.changeBlockItem(items, props.itemIndex);
        })
        return () => {
            return <div class="block-item" style={blockStyle.value} ref={blockRef}>
                {componentRender()}
            </div>
        }
    }
})